package com.service.abolishing.service.impl;

import com.service.abolishing.dao.CloudCampusInfoDao;
import com.service.abolishing.dto.CheckTenantDto;
import com.service.abolishing.entity.CloudCampusInfo;
import com.service.abolishing.service.CloudCampusInfoService;
import com.service.abolishing.task.CloudCampusApi;
import com.service.config.dto.ScreenUserDto;
import com.service.config.dto.SiteDto;
import com.service.config.utils.IdUtil;
import com.service.config.utils.ModelMapperUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * openApi用户表(CloudCampusInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-10-21 14:14:31
 */
@Service("cloudCampusInfoService")
public class CloudCampusInfoServiceImpl implements CloudCampusInfoService {
    @Resource
    private CloudCampusInfoDao cloudCampusInfoDao;
    @Resource
    RestTemplate restTemplate;
    @Resource
    CloudCampusApi cloudCampusApi;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CloudCampusInfo queryById(String id) {
        return this.cloudCampusInfoDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<CloudCampusInfo> queryAllByLimit(int offset, int limit) {
        return this.cloudCampusInfoDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param cloudCampusInfo 实例对象
     * @return 实例对象
     */
    @Override
    public CloudCampusInfo insert(CloudCampusInfo cloudCampusInfo) {
        this.cloudCampusInfoDao.insert(cloudCampusInfo);
        return cloudCampusInfo;
    }

    /**
     * 修改数据
     *
     * @param cloudCampusInfo 实例对象
     * @return 实例对象
     */
    @Override
    public CloudCampusInfo update(CloudCampusInfo cloudCampusInfo) {
        this.cloudCampusInfoDao.update(cloudCampusInfo);
        return this.queryById(cloudCampusInfo.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.cloudCampusInfoDao.deleteById(id) > 0;
    }

    @Override
    public Map check(CheckTenantDto checkTenantDto, String userId) {
        return check(checkTenantDto);
    }

    @Override
    public List<CloudCampusInfo> insertOrUpdate(CloudCampusInfo strictMap, String userId) {
        CloudCampusInfo screenUser = new CloudCampusInfo();
        screenUser.setTenantName(strictMap.getTenantName());
        screenUser.setManageId(userId);
        screenUser.setDomain(strictMap.getDomain());
        List<CloudCampusInfo> screenUsers = cloudCampusInfoDao.queryAll(screenUser);
        if (screenUsers.size() > 0) {
            return screenUsers;
        } else {
            strictMap.setId(IdUtil.getStringId());
            strictMap.setManageId(userId);
            strictMap.setSecret(random(UUID.randomUUID().toString()));
            strictMap.setStatus(true);
            cloudCampusInfoDao.insert(strictMap);
            return null;
        }
    }

    @Override
    public void updateApiAccount(CloudCampusInfo strictMap) {
        cloudCampusInfoDao.update(strictMap);
    }

    @Override
    public void serviceStatusBind(String screen_user_id, Boolean status, String userId, String domain) {
        CloudCampusInfo screenUser1 = new CloudCampusInfo();
        screenUser1.setManageId(userId);
        screenUser1.setDomain(domain);
        List<CloudCampusInfo> screenUsers = cloudCampusInfoDao.queryAll(screenUser1);
        List<CloudCampusInfo> collect = screenUsers.stream().filter(screenUser2 -> !screenUser2.getId().equals(screen_user_id)).collect(Collectors.toList());
        collect.stream().forEach(screenUser2 -> {
            if (status) {
                screenUser2.setStatus(false);
            }
        });
        List<CloudCampusInfo> collect1 = screenUsers.stream().filter(screenUser2 -> screenUser2.getId().equals(screen_user_id)).collect(Collectors.toList());
        collect1.stream().forEach(screenUser -> {
            screenUser.setManageId(userId);
            screenUser.setId(screen_user_id);
            screenUser.setStatus(status);
        });
        cloudCampusInfoDao.insertOrUpdateBatch(screenUsers);
    }

    @Override
    public List<ScreenUserDto> queryAll(String userId) {
        CloudCampusInfo screenUser = new CloudCampusInfo();
        screenUser.setManageId(userId);
        List<CloudCampusInfo> list = cloudCampusInfoDao.queryAll(screenUser);
        return  ModelMapperUtil.strictMapList(list, ScreenUserDto.class);
    }

    @Override
    public CloudCampusInfo freshSecret(String cloudCampusId) {
        CloudCampusInfo cloudCampusInfo = new CloudCampusInfo();
        cloudCampusInfo.setId(cloudCampusId);
        String s = random(UUID.randomUUID().toString());
        cloudCampusInfo.setSecret(s);
        cloudCampusInfoDao.update(cloudCampusInfo);
        return this.queryById(cloudCampusId);
    }

    private String random(String toString) {
        CloudCampusInfo cloudCampusInfo = new CloudCampusInfo();
        cloudCampusInfo.setSecret(toString);
        CloudCampusInfo cloudCampusInfo1 = cloudCampusInfoDao.queryBySecret(cloudCampusInfo);
        if (cloudCampusInfo1 != null) {
            cloudCampusInfo.setSecret(UUID.randomUUID().toString());
            random(cloudCampusInfo.getSecret());
        }
        return toString;
    }

    @Override
    public void updateValidator(String screen_id, String validator) {
        CloudCampusInfo cloudCampusInfo = new CloudCampusInfo();
        cloudCampusInfo.setId(screen_id);
        cloudCampusInfo.setValidator(validator);
        cloudCampusInfoDao.update(cloudCampusInfo);
    }

    @Override
    public List<CloudCampusInfo> queryByValidator(String validator) {
        CloudCampusInfo cloudCampusInfo = new CloudCampusInfo();
        cloudCampusInfo.setValidator(validator);
        return cloudCampusInfoDao.queryAll(cloudCampusInfo);
    }

    @Override
    public CloudCampusInfo queryBySecret(String secret) {
        CloudCampusInfo cloudCampusInfo = new CloudCampusInfo();
        cloudCampusInfo.setSecret(secret);
        return cloudCampusInfoDao.queryBySecret(cloudCampusInfo);
    }

    /**
     * 校验云管api
     * @param checkTenantDto
     * @return
     */
    public Map check(CheckTenantDto checkTenantDto) {
        HashMap map = new HashMap();
        CloudCampusInfo screenUser = new CloudCampusInfo();
        screenUser.setTenantName(checkTenantDto.getUsername());
        List<CloudCampusInfo> screenUsers = cloudCampusInfoDao.queryAll(screenUser);
        //该账号是否存在
        if (screenUsers.size() > 0) {
            map.put("errorMsg","关联华为云管理账号已存在");
        }else {
            HttpHeaders requestHeaders = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            requestHeaders.setContentType(type);
            requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
            String token = cloudCampusApi.getToken(checkTenantDto.getUsername(), checkTenantDto.getPassword(), requestHeaders, checkTenantDto.getDomain());
            if (token == null) {
                map.put("errorMsg", "华为云管理账号不存在");
            } else {
                //获取站点
                requestHeaders.add("X-AUTH-TOKEN", token);
                CloudCampusInfo cloudCampusInfo = new CloudCampusInfo();
                cloudCampusInfo.setDomain(checkTenantDto.getDomain());
                cloudCampusInfo.setTenantName(checkTenantDto.getUsername());
                cloudCampusInfo.setTenantPwd(checkTenantDto.getPassword());
                List<SiteDto> sites = cloudCampusApi.getSites(requestHeaders, cloudCampusInfo);
                if (sites != null && sites.size() > 0) {
                    return map;
                }
                map.put("errorMsg", "该账号为租户账号，请使用正确的Api账号");
            }
        }
        return map;
    }
}
